import Vue from 'vue'
import Toast from './toast'

// 保证同一时间只有一个toast显示
let singleToast = true
let queue = []

function createInstance () {
  if (!queue.length || !singleToast) {
    const ToastConstructor = Vue.extend(Toast)
    const toastDom = new ToastConstructor({
      el: document.createElement('div')
    })
    document.body.appendChild(toastDom.$el)
    queue.push(toastDom)
    singleToast = true
    return toastDom
  }
}

// 注册成为全局组件
function toast (options = {}) {
  const toastDom = createInstance()
  toastDom.duration = options.duration || 3000
  toastDom.position = options.position || 'bottom'
  toastDom.content = options.content || '该歌曲没有版权，臣妾无能为力:('
  toastDom.show = singleToast = true
  setTimeout(() => {
    toastDom.show = singleToast = false
  }, toastDom.duration)
}

Vue.prototype.$toast = toast
export default toast
